package com.youdoneed.community.group.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.youdoneed.user.model.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.youdoneed.base.application.AppException;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.forum.dao.ForumnoticeMapper;
import com.youdoneed.community.forum.entity.Forumnotice;
import com.youdoneed.community.forum.service.ForumServciceStatic;
import com.youdoneed.community.group.dao.ForumgroupMapper;
import com.youdoneed.community.group.dao.ForumuserapplyjoingrouprecordMapper;
import com.youdoneed.community.group.dao.ForumuserinforumgroupMapper;
import com.youdoneed.community.group.entity.Forumgroup;
import com.youdoneed.community.group.entity.Forumuserapplyjoingrouprecord;
import com.youdoneed.community.group.entity.Forumuserinforumgroup;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.user.feign.UserFeignClient;

@Service
public class ForumuserapplyjoingrouprecordService {

    private final Logger logger = LoggerFactory.getLogger(ForumuserapplyjoingrouprecordService.class);

    @Autowired
    ForumuserapplyjoingrouprecordMapper forumuserapplyjoingrouprecordMapper;

    @Autowired
    ForumgroupMapper forumgroupMapper;

    @Autowired
    ForumuserinforumgroupMapper forumuserinforumgroupMapper;

    @Autowired
    FriendsClient friendsClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    ForumnoticeMapper forumnoticeMapper;

    public String privacy = null;

    /**
     * 申请加入小组
     *
     * @param userId
     * @param forumGroupId
     * @author lixs
     * @Date 2017.9.23
     */
    @Transactional
    public int saveApplyJoinGroupRecord(String userId, String forumGroupId) {
        logger.info("saveForumGroup");
        if (!StringUtils.hasText(forumGroupId)) {
            throw new AppException("小组id不能为空");
        }
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户id不能为空");
        }

        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumGroupId);
        if (forumgroup == null) {
            throw new AppException("该小组不存在");
        }
        if (forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)) {
            throw new AppException("该小组已经被解散");
        }
        if (forumgroup.getMemberCount() >= 2000) {
            throw new AppException("小组成员不能超过2000人 ");
        }

        if (forumgroup.getPrivacySetting() == ForumgroupStatic.privacy_public) {
            privacy = "公开";
        }
        if (forumgroup.getPrivacySetting() == ForumgroupStatic.privacy_close) {
            privacy = "封闭";
        }
        if (forumgroup.getPrivacySetting() == ForumgroupStatic.privacy_private) {
            privacy = "私密";
        }
        //用于统计群组未审核的人数
        int count = forumuserapplyjoingrouprecordMapper.countPeopleToBeAudited(forumGroupId);

        //判断该用户是否在小组中。可能该用户是通过别人邀请进入的小组
        Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumGroupId);
        if (forumuserinforumgroup != null) {
            throw new AppException("您已经在本小组中，无法再次申请加入");
        }
        //判断该用户有没有发送过加群申请
        Forumuserapplyjoingrouprecord applyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumGroupId);
        //用户未发送过加群申请
        if (null == applyjoingrouprecord) {

            logger.info("记录为空");
            //如果该群是公开群，则不需要群主同意就可以加入该群。
            if (forumgroup.getPrivacySetting() == ForumgroupStatic.privacy_public) {

                logger.info("第一次申请加群");
                //如果是第一次申请加群，则添加申请记录
                Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = new Forumuserapplyjoingrouprecord();
                //申请加入公开群无需审核，将申请状态改为同意加入
                forumuserapplyjoingrouprecord.setApplyStatus(ForumgroupStatic.apply_status_agree);
                forumuserapplyjoingrouprecord.setCreateDate(new Date());
                forumuserapplyjoingrouprecord.setForumGroupId(forumGroupId);
                forumuserapplyjoingrouprecord.setUserApplyJoinGroupRecordId(StringUUIdUtil.getUUID());
                forumuserapplyjoingrouprecord.setUserId(userId);
                forumuserapplyjoingrouprecordMapper.insert(forumuserapplyjoingrouprecord);

                //调用环信接口，添加群组成员（单个）
                friendsClient.addGroupUser(forumgroup.getHuanxinGroupId(), userId);

//			//修改用户申请表中的申请状态,将正在申请改为已同意
//			Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecords = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumGroupId);
//			forumuserapplyjoingrouprecords.setApplyStatus(ForumgroupStatic.apply_status_agree);
//			forumuserapplyjoingrouprecordMapper.updateByPrimaryKey(forumuserapplyjoingrouprecords);

                //进群后创建用户与小组的关联记录
                Forumuserinforumgroup forumuserinforumgroupnew = new Forumuserinforumgroup();
                forumuserinforumgroupnew.setCreateDate(new Date());
                forumuserinforumgroupnew.setForumGroupId(forumGroupId);
                forumuserinforumgroupnew.setUserId(userId);
                forumuserinforumgroupnew.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
                forumuserinforumgroupnew.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
                forumuserinforumgroupnew.setUserInForumGroupId(StringUUIdUtil.getUUID());
                forumuserinforumgroupMapper.insert(forumuserinforumgroupnew);

                //获取群成员的总数
                List<Forumuserinforumgroup> forumuserinforumgroupNew = forumuserinforumgroupMapper.selectByGroupId(forumGroupId);

                //进群后，更新群成员人数
                forumgroup.setMemberCount(forumuserinforumgroupNew.size());

                //如果申请加入公开群，则发出相应通知给群主
                logger.info("添加记录啊");
                Forumnotice forumnotice = new Forumnotice();
                forumnotice.setCreateDate(new Date());
                forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
                forumnotice.setNoticeType(ForumServciceStatic.ApplyForPublic);
                forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(userId).getData().getImageUrl());
                forumnotice.setNoticeUserId(userId);
                forumnotice.setNoticeUserNickname(userFeignClient.getUser(userId).getData().getName());
                forumnotice.setReadStatus(0);
                forumnotice.setSourceDesc(forumgroup.getGroupName());
                forumnotice.setSourceId(forumGroupId);
                forumnotice.setUserId(forumgroup.getLeaderUserId());
                forumnoticeMapper.insertSelective(forumnotice);

                return forumgroupMapper.updateByPrimaryKey(forumgroup);
            }
            //如果是第一次申请加群，则添加申请记录
            Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = new Forumuserapplyjoingrouprecord();
            forumuserapplyjoingrouprecord.setApplyStatus(ForumgroupStatic.apply_status_ing);
            forumuserapplyjoingrouprecord.setCreateDate(new Date());
            forumuserapplyjoingrouprecord.setForumGroupId(forumGroupId);
            forumuserapplyjoingrouprecord.setUserApplyJoinGroupRecordId(StringUUIdUtil.getUUID());
            forumuserapplyjoingrouprecord.setUserId(userId);
            forumuserapplyjoingrouprecordMapper.insert(forumuserapplyjoingrouprecord);

            //如果申请加入非公开群，则发出相应通知给群主
            Forumnotice forumnotice = new Forumnotice();
            forumnotice.setCreateDate(new Date());
            forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
            forumnotice.setNoticeType(ForumServciceStatic.ApplyForPrivacy);
            forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(userId).getData().getImageUrl());
            forumnotice.setNoticeUserId(userId);
            forumnotice.setNoticeUserNickname(userFeignClient.getUser(userId).getData().getName());
            forumnotice.setReadStatus(0);
            forumnotice.setSourceDesc(forumgroup.getGroupName());
            forumnotice.setSourceId(forumGroupId);
            forumnotice.setUserId(forumgroup.getLeaderUserId());
            forumnoticeMapper.insertSelective(forumnotice);


            //更新统计该群未审核的人数
            forumgroup.setCountPeopleToBeAudited(count + 1);
            forumgroupMapper.updateByPrimaryKeySelective(forumgroup);
            return 0;
        }
        //该用户发送过加群的请求,该请求还未处理
        if (applyjoingrouprecord.getApplyStatus().equals(ForumgroupStatic.apply_status_ing)) {
            throw new AppException("您的申请还未被处理，无法再次申请加群");
        }

        //该用户之前发送的请求被拒绝或者自己退出群
        if (applyjoingrouprecord.getApplyStatus().equals(ForumgroupStatic.apply_status_refuse) || applyjoingrouprecord.getApplyStatus().equals(ForumgroupStatic.not_in_group)) {
            logger.info("第一个循环");
            //如果该群是公开群，则不需要群主同意就可以加入该群。
            if (forumgroup.getPrivacySetting() == ForumgroupStatic.privacy_public) {

                logger.info("这是一个公开群");

                //调用环信接口，添加群组成员（单个）
                friendsClient.addGroupUser(forumgroup.getHuanxinGroupId(), userId);

                //修改用户申请表中的申请状态,将正在申请改为已同意
                Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecords = forumuserapplyjoingrouprecordMapper.selectByUseridAndForumGroupId(userId, forumGroupId);
                forumuserapplyjoingrouprecords.setApplyStatus(ForumgroupStatic.apply_status_agree);
                forumuserapplyjoingrouprecordMapper.updateByPrimaryKey(forumuserapplyjoingrouprecords);

                //进群后创建用户与小组的关联记录
                Forumuserinforumgroup forumuserinforumgroupnew = new Forumuserinforumgroup();
                forumuserinforumgroupnew.setCreateDate(new Date());
                forumuserinforumgroupnew.setForumGroupId(forumGroupId);
                forumuserinforumgroupnew.setUserId(userId);
                forumuserinforumgroupnew.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
                forumuserinforumgroupnew.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
                forumuserinforumgroupnew.setUserInForumGroupId(StringUUIdUtil.getUUID());
                forumuserinforumgroupMapper.insert(forumuserinforumgroupnew);

                //获取群成员总数
                List<Forumuserinforumgroup> forumuserinforumgroupNew = forumuserinforumgroupMapper.selectByGroupId(forumGroupId);

                //如果申请加入公开群，则发出相应通知给群主
                Forumnotice forumnotice = new Forumnotice();
                forumnotice.setCreateDate(new Date());
                forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
                forumnotice.setNoticeType(ForumServciceStatic.ApplyForPublic);
                forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(userId).getData().getImageUrl());
                forumnotice.setNoticeUserId(userId);
                forumnotice.setNoticeUserNickname(userFeignClient.getUser(userId).getData().getName());
                forumnotice.setReadStatus(0);
                forumnotice.setSourceDesc(forumgroup.getGroupName());
                forumnotice.setSourceId(forumGroupId);
                forumnotice.setUserId(forumgroup.getLeaderUserId());
                forumnoticeMapper.insertSelective(forumnotice);

                //进群后，更新群组人数
                forumgroup.setMemberCount(forumuserinforumgroupNew.size());
                return forumgroupMapper.updateByPrimaryKey(forumgroup);
            }

            logger.info("群为非公开群");

            //如果申请加入非公开群，则发出相应通知给群主
            Forumnotice forumnotice = new Forumnotice();
            forumnotice.setCreateDate(new Date());
            forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
            forumnotice.setNoticeType(ForumServciceStatic.ApplyForPrivacy);
            forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(userId).getData().getImageUrl());
            forumnotice.setNoticeUserId(userId);
            forumnotice.setNoticeUserNickname(userFeignClient.getUser(userId).getData().getName());
            forumnotice.setReadStatus(0);
            forumnotice.setSourceDesc(forumgroup.getGroupName());
            forumnotice.setSourceId(forumGroupId);
            forumnotice.setUserId(forumgroup.getLeaderUserId());
            forumnoticeMapper.insertSelective(forumnotice);

            applyjoingrouprecord.setApplyStatus(ForumgroupStatic.apply_status_ing);
            applyjoingrouprecord.setCreateDate(new Date());
            forumuserapplyjoingrouprecordMapper.updateByPrimaryKeySelective(applyjoingrouprecord);
            //更新统计该群未审核的人数
            forumgroup.setCountPeopleToBeAudited(count + 1);
            forumgroupMapper.updateByPrimaryKeySelective(forumgroup);
            return 0;
        }

        return 0;
    }

    /**
     * 处理加入小组的申请
     *
     * @param userApplyJoinGroupRecordId
     * @param applyStatus
     * @return int
     * @author lixs
     * @date 2017.6.25
     */
    @Transactional
    public int manageJoinGroupApplication(String leaderUserId, String userApplyJoinGroupRecordId, Integer applyStatus) {
        logger.info("处理加入小组的申请");
        if (!StringUtils.hasText(userApplyJoinGroupRecordId)) {
            throw new AppException("主键id不能为空");
        }
        if (!StringUtils.hasText(leaderUserId)) {
            throw new AppException("群主id不能为空");
        }
        if (applyStatus == null) {
            throw new AppException("申请状态不能为空");
        }
        Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = forumuserapplyjoingrouprecordMapper.selectByPrimaryKey(userApplyJoinGroupRecordId);
        if (forumuserapplyjoingrouprecord == null) {
            throw new AppException("未能查到该申请记录");
        }
        if (forumuserapplyjoingrouprecord.getApplyStatus() != ForumgroupStatic.apply_status_ing) {
            throw new AppException("该申请记录已经被处理，无法对其进行操作");
        }
        Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumuserapplyjoingrouprecord.getForumGroupId());
        if (null == forumgroup) {
            throw new AppException("群组信息为空");
        }
        if (forumgroup.getMemberCount() >= 2000) {
            throw new AppException("小组成员不能超过2000人 ");
        }
        if (!leaderUserId.equals(forumgroup.getLeaderUserId())) {
            throw new AppException("您不是群主，无法处理申请");
        }
        //获取该群组未审核的人数
        int count = forumuserapplyjoingrouprecordMapper.countPeopleToBeAudited(forumgroup.getForumGroupId());
        User appliedUser = userFeignClient.getUser(forumuserapplyjoingrouprecord.getUserId()).getData();
        if (applyStatus == ForumgroupStatic.apply_status_agree) {
            //更改申请状态
            forumuserapplyjoingrouprecord.setApplyStatus(applyStatus);
            forumuserapplyjoingrouprecordMapper.updateByPrimaryKey(forumuserapplyjoingrouprecord);
            //调用环信接口，添加群组成员（单个）
            friendsClient.addGroupUser(forumgroup.getHuanxinGroupId(), forumuserapplyjoingrouprecord.getUserId());


            //进群后创建用户与小组的关联记录
            Forumuserinforumgroup forumuserinforumgroupnew = new Forumuserinforumgroup();
            forumuserinforumgroupnew.setCreateDate(new Date());
            forumuserinforumgroupnew.setForumGroupId(forumuserapplyjoingrouprecord.getForumGroupId());
            forumuserinforumgroupnew.setUserId(forumuserapplyjoingrouprecord.getUserId());
            forumuserinforumgroupnew.setUserInForumGroupId(StringUUIdUtil.getUUID());
            forumuserinforumgroupnew.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
            forumuserinforumgroupnew.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
            forumuserinforumgroupMapper.insert(forumuserinforumgroupnew);

            //加群成功后，发送通知给用户
            Forumnotice forumnotice = new Forumnotice();
            forumnotice.setCreateDate(new Date());
            forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
            forumnotice.setNoticeType(ForumServciceStatic.AgreeApplyForPrivacyGroup);
            forumnotice.setNoticeUserHeadUrl(appliedUser.getImageUrl());
            forumnotice.setNoticeUserId(forumgroup.getLeaderUserId());
            forumnotice.setNoticeUserNickname(appliedUser.getName());
            forumnotice.setReadStatus(0);
            forumnotice.setSourceDesc(forumgroup.getGroupName());
            forumnotice.setSourceId(forumuserapplyjoingrouprecord.getForumGroupId());
            forumnotice.setUserId(forumuserapplyjoingrouprecord.getUserId());
            forumnoticeMapper.insertSelective(forumnotice);

            //获取群成员总数
            List<Forumuserinforumgroup> forumuserinforumgroupNew = forumuserinforumgroupMapper.selectByGroupId(forumuserapplyjoingrouprecord.getForumGroupId());

            //进群后，更新群组人数
            forumgroup.setMemberCount(forumuserinforumgroupNew.size());
            //更新群审核人数
            forumgroup.setCountPeopleToBeAudited(count - 1);
            return forumgroupMapper.updateByPrimaryKey(forumgroup);
        }
        if (applyStatus == ForumgroupStatic.apply_status_refuse || applyStatus == ForumgroupStatic.not_in_group) {
            User groupLeader = userFeignClient.getUser(forumgroup.getLeaderUserId()).getData();
            //加群失败后，发送通知给用户
            Forumnotice forumnotice = new Forumnotice();
            forumnotice.setCreateDate(new Date());
            forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
            forumnotice.setNoticeType(ForumServciceStatic.RefuseApplyForPrivacyGroup);
            forumnotice.setNoticeUserHeadUrl(groupLeader.getImageUrl());
            forumnotice.setNoticeUserId(forumgroup.getLeaderUserId());
            forumnotice.setNoticeUserNickname(groupLeader.getName());
            forumnotice.setReadStatus(0);
            forumnotice.setSourceDesc(forumgroup.getGroupName());
            forumnotice.setSourceId(forumuserapplyjoingrouprecord.getForumGroupId());
            forumnotice.setUserId(appliedUser.getUserId());
            forumnoticeMapper.insertSelective(forumnotice);

            //更改申请状态
            forumuserapplyjoingrouprecord.setApplyStatus(applyStatus);
            forumuserapplyjoingrouprecordMapper.updateByPrimaryKey(forumuserapplyjoingrouprecord);
            //跟新群审核人数
            forumgroup.setCountPeopleToBeAudited(count - 1);
            forumgroupMapper.updateByPrimaryKeySelective(forumgroup);
            return 0;
        }
        return 0;
    }

    /**
     * 获取申请列表
     *
     * @param groupId
     * @param currentPage
     * @param rows
     * @return List<String>
     * @author lixs
     * @Date 2017.7.8
     */
    @Transactional
    public List<Forumuserapplyjoingrouprecord> getApplicationByGroupId(String groupId, Integer currentPage, Integer rows) {
        logger.info("获取申请列表");
        if (!StringUtils.hasText(groupId)) {
            throw new AppException("小组id不能为空");
        }
        PageHelper.startPage(currentPage, rows);
        List<Forumuserapplyjoingrouprecord> forumuserapplyjoingrouprecord = forumuserapplyjoingrouprecordMapper.getApplicationByGroupId(groupId);
        if (forumuserapplyjoingrouprecord == null) {
            throw new AppException("未获取到邀请列表");
        }
        return forumuserapplyjoingrouprecord;
    }


}
